import datetime

from flask import request, jsonify, current_app

from ihome import db
from ihome.models import Order, User, House
from ihome.modules.api import api_blu

# 添加订单
from ihome.utils.response_code import RET, error_map


@api_blu.route('/orders', methods=['POST'])
def orders():
    # 判断用户是否登陆

    # 获取参数
    house_id = request.json.get("house_id")
    start_date = request.json.get("start_date")
    end_date = request.json.get("end_date")

    # 校验参数
    if not all([house_id, start_date, end_date]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        house_id = int(house_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 计算租房时间
    try:
        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        days = (end_date - start_date).days
        print(days)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="日期是否正确")

    # 查询是否有此房屋
    try:
        house = House.query.get(house_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not house:
        return jsonify(errno=RET.DBERR, errmsg="没有此房屋")

    # 查看时间冲突的订单
    try:
        count = Order.query.filter(Order.begin_date <= Order.end_date, Order.end_date >= Order.begin_date,
                                   Order.house_id == house_id).count()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg=error_map[RET.DBERR])
    if count > 0:
        return jsonify(errno=RET.DBERR, errmsg="房屋重复了")

    # 判断是否是自己的房屋

    # 生成订单
    try:
        order = Order()
        order.house_id = house_id
        order.start_date = start_date
        order.end_date = end_date
        # order.user_id = userid
        order.days = days
        order.house_price = house.price
        order.amount = days * house.price

        db.session.add(order)
        db.session.commit()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="生成订单失败")

    data = {
        "order_id": order.id
    }

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)


# 获取订单列表
@api_blu.route('/orders')
def get_orders():

    # 获取参数
    role = request.args.get("role",)

    # 校验参数
    if not role:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 数据库行为:查询订单
    # 判断用户
    if role == "custom":  # 顾客的订单
        try:
            orders =Order.query.filter(Order.user_id == user.id).order_by(Order.create_time.desc()).all()
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    else:  # 房东的房屋
        try:
            # 房东的所有房屋
            # 房东订单中的房屋
            # 房屋那些房屋在订单中

            # 房东的所有房屋
            hourses = House.query.filter(House.user_id == user_id).all()

            # 房东订单中的房屋
            # 房屋那些房屋在订单中
            orders = Order.query.filter(Order.house_id.in_(hourses)).order_by(Order.create_time.desc()).all()
        except Exception as e:
            current_app.logger.error (e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])




    data = {
        "orders": [order.to_dict() for order in orders]
    }

    # json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
